<!DOCTYPE html>
<html lang="zh">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>智能聊天机器人</title>
    <style>
        * {
            margin: 0;
            padding: 0;
            box-sizing: border-box;
        }

        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
            padding: 20px;
            display: flex;
            justify-content: center;
            align-items: center;
        }

        #chat-container {
            width: 100%;
            max-width: 800px;
            height: 80vh;
            background: rgba(255, 255, 255, 0.95);
            border-radius: 20px;
            box-shadow: 0 20px 40px rgba(0, 0, 0, 0.1);
            -webkit-backdrop-filter: blur(10px);
            backdrop-filter: blur(10px);
            display: flex;
            flex-direction: column;
            overflow: hidden;
        }

        #header {
            background: linear-gradient(135deg, #4CAF50, #45a049);
            color: white;
            padding: 20px;
            text-align: center;
            box-shadow: 0 2px 10px rgba(0, 0, 0, 0.1);
        }

        #header h2 {
            margin: 0;
            font-size: 1.5em;
            font-weight: 300;
        }

        #config-info {
            font-size: 0.8em;
            opacity: 0.9;
            margin-top: 5px;
        }

        #messages {
            flex: 1;
            overflow-y: auto;
            padding: 20px;
            background: #f8f9fa;
        }

        .msg {
            margin: 15px 0;
            display: flex;
            align-items: flex-start;
            animation: fadeIn 0.3s ease-in;
        }

        @keyframes fadeIn {
            from {
                opacity: 0;
                transform: translateY(10px);
            }
            to {
                opacity: 1;
                transform: translateY(0);
            }
        }

        .bot {
            justify-content: flex-start;
        }

        .msg-content {
            max-width: 70%;
            padding: 12px 16px;
            border-radius: 18px;
            line-height: 1.4;
            position: relative;
        }

        .user .msg-content {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
            margin-left: auto;
        }

        .bot .msg-content {
            background: white;
            color: #333;
            border: 1px solid #e9ecef;
            box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
        }

        .sender {
            font-weight: 600;
            font-size: 0.8em;
            margin-bottom: 4px;
            opacity: 0.8;
        }

        #input-area {
            padding: 20px;
            background: white;
            border-top: 1px solid #e9ecef;
            display: flex;
            gap: 10px;
            align-items: center;
        }

        #user-input {
            flex: 1;
            padding: 12px 16px;
            border: 2px solid #e9ecef;
            border-radius: 25px;
            font-size: 14px;
            outline: none;
            transition: all 0.3s ease;
        }

        #user-input:focus {
            border-color: #007bff;
            box-shadow: 0 0 0 3px rgba(0, 123, 255, 0.1);
        }

        #send-btn, #clear-btn {
            padding: 12px 20px;
            border: none;
            border-radius: 25px;
            font-size: 14px;
            font-weight: 600;
            cursor: pointer;
            transition: all 0.3s ease;
            min-width: 80px;
        }

        #send-btn {
            background: linear-gradient(135deg, #007bff, #0056b3);
            color: white;
        }

        #send-btn:hover:not(:disabled) {
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0, 123, 255, 0.4);
        }

        #send-btn:disabled {
            background: #6c757d;
            cursor: not-allowed;
            transform: none;
        }

        #clear-btn {
            background: #6c757d;
            color: white;
        }

        #clear-btn:hover {
            background: #5a6268;
            transform: translateY(-2px);
        }

        @keyframes spin {
            0% {
                transform: rotate(0deg);
            }
            100% {
                transform: rotate(360deg);
            }
        }

        @media (max-width: 768px) {
            body {
                padding: 10px;
            }

            #chat-container {
                height: 90vh;
                border-radius: 10px;
            }

            .msg-content {
                max-width: 85%;
            }

            #input-area {
                padding: 15px;
                flex-direction: column;
                gap: 10px;
            }

            #user-input {
                width: 100%;
            }

            .button-group {
                display: flex;
                gap: 10px;
                width: 100%;
            }

            #send-btn, #clear-btn {
                flex: 1;
            }
        }
    </style>
</head>
<body>

<div id="chat-container">
    <div id="header">
        <h2>智能聊天机器人</h2>
        <div id="config-info"></div>
    </div>

    <div id="messages">
        <div class="msg bot">
            <div class="msg-content">
                <div class="sender">AI助手</div>
                你好！我是智能聊天机器人，有什么可以帮助你的吗？
            </div>
        </div>
    </div>

    <div id="input-area">
        <label for="user-input"></label>
        <input type="text" id="user-input" placeholder="请输入你的问题..." maxlength="1000"/>
        <div class="button-group">
            <button id="send-btn" onclick="sendMessage()">发送</button>
            <button id="clear-btn" onclick="clearChat()">清空</button>
        </div>
    </div>
</div>

<script>
    let conversationHistory = [];
    let isWaiting = false;

    // 页面加载完成后获取配置信息
    document.addEventListener('DOMContentLoaded', function () {
        loadConfig();

        // 回车发送消息
        document.getElementById('user-input').addEventListener('keypress', function (e) {
            if (e.key === 'Enter' && !e.shiftKey) {
                e.preventDefault();
                sendMessage();
            }
        });
    });

    function loadConfig() {
        fetch('/config')
            .then(res => res.json())
            .then(config => {
                const configInfo = document.getElementById('config-info');
                configInfo.textContent = `模型: ${config.model} | API: ${config.api_configured ? '已配置' : '未配置'}`;
            })
            .catch(err => {
                console.error('获取配置失败:', err);
            });
    }

    function sendMessage() {
        if (isWaiting) return;

        const input = document.getElementById("user-input");
        const msg = input.value.trim();

        if (!msg) {
            input.focus();
            return;
        }

        // 添加用户消息
        addMessage("你", msg, "user");

        // 添加到对话历史
        conversationHistory.push({
            role: "user",
            content: msg
        });

        // 清空输入框并禁用发送按钮
        input.value = "";
        setWaiting(true);

        // 添加加载指示器
        const loadingMsg = addMessage("AI助手", '<div class="loading"></div> 正在思考...', "bot");

        // 发送请求
        fetch("/chat", {
            method: "POST",
            headers: {"Content-Type": "application/json"},
            body: JSON.stringify({
                message: msg,
                history: conversationHistory.slice(-10) // 只发送最近10轮对话
            })
        })
            .then(res => res.json())
            .then(data => {
                // 移除加载指示器
                loadingMsg.remove();

                if (data.error) {
                    addMessage("系统", data.response, "bot error");
                } else {
                    addMessage("AI助手", data.response, "bot");

                    // 添加到对话历史
                    conversationHistory.push({
                        role: "assistant",
                        content: data.response
                    });
                }

                setWaiting(false);
            })
            .catch(err => {
                console.error('发送消息失败:', err);
                loadingMsg.remove();
                addMessage("系统", "抱歉，网络连接出现问题，请稍后再试。", "bot error");
                setWaiting(false);
            });
    }

    function addMessage(sender, text, cls) {
        const msgDiv = document.createElement("div");
        msgDiv.className = "msg " + cls.split(' ')[0];

        const contentDiv = document.createElement("div");
        contentDiv.className = "msg-content" + (cls.includes('error') ? ' error' : '');

        const senderDiv = document.createElement("div");
        senderDiv.className = "sender";
        senderDiv.textContent = sender;

        const textDiv = document.createElement("div");
        textDiv.innerHTML = text;

        contentDiv.appendChild(senderDiv);
        contentDiv.appendChild(textDiv);
        msgDiv.appendChild(contentDiv);

        const messagesContainer = document.getElementById("messages");
        messagesContainer.appendChild(msgDiv);

        // 滚动到底部
        messagesContainer.scrollTop = messagesContainer.scrollHeight;

        return msgDiv;
    }

    function setWaiting(waiting) {
        isWaiting = waiting;
        const sendBtn = document.getElementById('send-btn');
        const input = document.getElementById('user-input');

        sendBtn.disabled = waiting;
        input.disabled = waiting;

        if (waiting) {
            sendBtn.textContent = '发送中...';
        } else {
            sendBtn.textContent = '发送';
            input.focus();
        }
    }

    function clearChat() {
        if (confirm('确定要清空聊天记录吗？')) {
            document.getElementById('messages').innerHTML = `
            <div class="msg bot">
                <div class="msg-content">
                <div class="sender">AI助手</div>
                你好！我是智能聊天机器人，有什么可以帮助你的吗？
                </div>
            </div>
            `;
            conversationHistory = [];
            document.getElementById('user-input').focus();
        }
    }
</script>

</body>
</html>